<!--
 * @Author: your name
 * @Date: 2022-02-18 15:07:38
 * @LastEditTime: 2022-11-18 14:20:29
 * @LastEditors: Aaron Huang
 * @LastEditTime: 2022-11-04 16:14:27
 * @LastEditors: Even Liu
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \ias_ui\src\views\coi\channelInventory\components\list.vue
-->
<template>
  <div v-loading="loading" class="purchase">
    <search-head :search-list="searchList" :search-data="searchData" :btn-list="btnList" :options="options" @handleSearch="handleSearch" @reset="reset" />
    <essTable
      ref="table"
      :thead-list="theadList(Boolean(isAdministration || isECOperate))"
      :resize-observer-ele="resizeObserverEle"
      :other-container-box="otherContainerBox"
      :page-num="searchData.pageNum + 1"
      :total="total"
      :data-list="dataList"
      row-key="upc"
      :selectable="selectable"
      @handlePageChange="handlePageChange"
      @selectionChange="selectionChange"
    >
      <template v-slot:imageUrl="{ scope }">
        <el-image class="mainImg" :src="scope.row.imageUrl || '' | transImgUrl" :preview-src-list="[scope.row.imageUrl || ''] | transImgUrl" />
      </template>
      <template v-slot:sku="{ scope }">
        <span class="el-button--text el-button--mini" @click="viewDetail(scope.row)">{{ scope.row.sku }}</span>
      </template>
      <template v-slot:categoryName="{ scope }">
        {{ scope.row.categoryName | categoryName }}
      </template>
      <template v-slot:skuChannelInfocategoryName="{ scope }">
        {{ scope.row.skuChannelInfo.categoryName }}
      </template>
      <template v-slot:channelSkuId="{ scope }">
        {{ scope.row.skuChannelInfo.channelSkuId }}
      </template>
      <template v-slot:goodsType="{ scope }">
        {{ scope.row.goodsType | transGoodsType }}
      </template>
      <template v-slot:skuChannelInfo="{ scope }">
        {{ scope.row.skuChannelInfo.channelBrandName }}
      </template>
      <template v-slot:skuChannelInfoskuCategories="{ scope }">
        {{ renderSkuCategoryTo(scope.row.skuChannelInfo.shopCategories) }}
      </template>
      <template v-slot:skuCategories="{ scope }">
        {{ renderSkuCategory(scope.row.skuCategories) }}
      </template>
      <template v-slot:lastPushResult="{ scope }">
        {{ scope.row.lastPushResult | pushResults }}
      </template>
      <template v-slot:skuChannelInfolastPushResult="{ scope }">
        {{ scope.row.skuChannelInfo.lastPushResult | pushResults }}
      </template>
      <template v-slot:lastPushFailMsg="{ scope }">
        {{ scope.row.skuChannelInfo.lastPushFailMsg }}
      </template>
      <template v-slot:handle="{ scope }">
        <div>
          <el-button v-if="filterHandle(scope.row.goodsType, scope.row)" type="text" size="mini" @click="edit(scope)">编辑</el-button>
          <el-button type="text" size="mini" @click="operationLog(scope)">操作日志</el-button>
        </div>
      </template>
      <div slot="right" name="right">
        <el-button :disabled="!multipleSelection.length" size="mini" type="primary" round @click="batchEdit('UpdateChannel')">批量发布渠道</el-button>
        <el-button :disabled="!multipleSelection.length" size="mini" type="primary" round @click="batchEdit('edit')">修改店内类目</el-button>
      </div>
    </essTable>
    <operation-log ref="operationLogRef" :table-data="logData" :log-list="channelInventoryLog">
      <template v-slot:pushDateTime="{ scope }">
        {{ scope.row.pushDateTime | transDate }}
      </template>
      <template v-slot:operationType="{ scope }">
        {{ scope.row.operationType | operationTypes }}
      </template>
      <template v-slot:pushResult="{ scope }">
        {{ scope.row.pushResult | pushResults }}
        <div v-if="scope.row.pushResult === 2">{{ scope.row.errorMsg }}</div>
      </template>
    </operation-log>
    <el-dialog :title="title" width="500px" :visible.sync="dialogVisible">
      <el-form ref="ruleForm" class="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item v-if="title === '批量修改店内类目'" label="店内类目" prop="category">
          <el-cascader
            ref="cascader"
            v-model="form.category"
            :props="{ children: 'children', label: 'categoryName', expandTrigger: 'hover', value: 'categoryId', multiple: true }"
            :options="options.shopCategoryId"
            separator=">"
            filterable
            clearable
            collapse-tags
            style="width: 280px"
            @change="handleChange"
          />
          <i class="el-icon-refresh el-button--text" title="点击刷新店内类目" @click="refreshGetChannelTreeList" />
        </el-form-item>
        <el-form-item v-if="title === '批量修改店内类目'" label="修改方式" prop="batchOperationType">
          <el-radio-group v-model="form.batchOperationType">
            <el-radio :label="1">追加</el-radio>
            <el-radio :label="2">覆盖</el-radio>
            <el-radio :label="3">删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-else label="备注">
          <el-input v-model="form.operationRemark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" :loading="btnloading" @click="onSubmit('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import essTable from '@/components/eTable/eTable.vue'
import searchHead from '@/components/searchHead/searchHead.vue'
import { channelInventoryList as theadList /* channelInventoryListTo */ } from '@/views/coi/commonJs/tableHeadList'
import operationLog from '@/views/coi/components/operationLog.vue'
import {
  findChgSkuChannelPage,
  queryTreeList,
  queryChannelTreeList,
  operationLogByUpcNbr,
  batchUpdateSkuShopCatByChannel,
  skuRepublishByChannel
} from '@/api/coi/onlineTaskAPI/sku'
import { releaseStatus, groundStatus, goodsTypeList, goodsType_CBEC, goodsType_NO_CBEC } from '@/views/coi/commonJs/dictionary.js'
import { channelInventoryLog } from '@/views/coi/commonJs/operationLogList'
import eventBus from '@/utils/eventBus'
import moment from 'moment'
import { authentication, filterKey, stringToArray } from '@/utils/processingData.js'
import { hasPower } from '../js/role'

export default {
  components: { searchHead, essTable, operationLog },
  filters: {
    transDate(v) {
      if (v === null) {
        return ''
      }
      return moment(v).format('YYYY-MM-DD HH:mm:ss')
    },
    operationTypes(v) {
      let result = ''
      switch (v) {
        case 0:
          result = '删除'
          break
        case 1:
          result = '新增'
          break
        case 2:
          result = '修改'
          break
      }
      return result
    },
    pushResults(v) {
      let result = ''
      switch (Number(v)) {
        case -1:
          result = '不推送'
          break
        case 0:
          result = '推送中'
          break
        case 1:
          result = '成功'
          break
        case 2:
          result = '失败'
          break
      }
      return result
    },
    categoryName(val) {
      return val?.replace(/&gt;/g, '>')
    },
    transImgUrl(url) {
      return authentication(url)
    },
    transGoodsType(v) {
      return filterKey(v, goodsTypeList)
    }
  },
  mixins: [hasPower],
  props: {
    menuName: {
      type: String,
      default: 'WMDJ'
    }
  },
  data() {
    return {
      loading: false,
      resizeObserverEle: ['.app-main', '.app-container'],
      otherContainerBox: ['.app-container', '.checkComponent', '.tab'],
      searchData: { channelBrandId: '' },
      options: {
        lastPushResult: releaseStatus,
        groundStatus,
        preSale: [
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ],
        dsvFlag: [
          { label: '是', value: 1 },
          { label: '否', value: 0 }
        ],
        categoryId: [],
        shopCategoryId: [],
        goodsType: []
      },
      btnList: [
        { name: '查询', icon: 'el-icon-search', event: 'handleSearch' },
        { name: '重置', icon: 'el-icon-refresh', event: 'reset' }
      ],
      total: 0,
      theadList,
      dataList: [],
      logData: [],
      channelInventoryLog,
      multipleSelection: [],
      title: '批量修改店内类目',
      dialogVisible: false,
      btnloading: false,
      form: {},
      rules: {
        category: [{ required: true, message: '请选择店内类目', trigger: 'change' }],
        batchOperationType: [{ required: true, message: '请选择修改方式', trigger: 'change' }]
      },
      skuCategories: [],
      goodsType_CBEC,
      goodsType_NO_CBEC
    }
  },
  computed: {
    channelId() {
      // console.log('this.menuName', this.menuName)
      if (this.menuName === 'WMDJ') return '12'
      else if (this.menuName === 'JDWX') return '06'
      return '07'
    },
    searchList() {
      const arr = []
      if (!window.hidden_CBEC_iteration && (this.isAdministration || this.isECOperate)) {
        arr.push({ label: '业务类型', type: 'select', value: 'goodsType', multiple: true })
      }
      if (this.menuName === 'WMDJ') {
        return [
          { label: 'UPC(不含检验码)', type: 'textarea', value: 'skuList' },
          { label: '渠道商品编号', type: 'input', value: 'channelSkuId' },
          { label: '商品名称', type: 'input', value: 'skuName' },
          ...arr,
          { label: '渠道品牌名称', type: 'brandName', value: 'channelBrandId', channelId: '12' },
          { label: '发布状态', type: 'select', value: 'lastPushResult' },
          { label: '是否预售', type: 'select', value: 'preSale' },
          { label: '渠道平台类目', type: 'cascader', value: 'categoryId' },
          // { label: '商品上下架状态', type: 'select', value: 'groundStatus' },
          { label: '是否大家电', type: 'select', value: 'dsvFlag' },
          { label: '渠道店铺类目', type: 'cascader', value: 'shopCategoryId' }
        ]
      }
      return [
        { label: 'UPC(不含检验码)', type: 'textarea', value: 'skuList' },
        { label: '渠道商品编号', type: 'input', value: 'channelSkuId' },
        { label: '商品名称', type: 'input', value: 'skuName' },
        ...arr,
        { label: '渠道品牌名称', type: 'brandName', value: 'channelBrandId', channelId: '07' },
        { label: '发布状态', type: 'select', value: 'lastPushResult' },
        { label: '渠道平台类目', type: 'cascader', value: 'categoryId' },
        { label: '渠道店铺类目', type: 'cascader', value: 'shopCategoryId' }
      ]
    }
  },
  watch: {
    menuName: {
      handler(val) {
        if (val === 'WMDJ') {
          this.otherContainerBox = ['.app-container', '.checkComponent', '.tab']
        } else {
          this.otherContainerBox = ['.app-container', '.tab']
        }
        this.searchData = {
          channelId: this.channelId,
          channelBrandId: '',
          pageNum: 0,
          pageSize: 10
        }
        // if (val === 'JDWX') {
        //   this.theadList = channelInventoryListTo
        // } else {
        //   this.theadList = channelInventoryList
        // }
        this.dataList = []
        this.getChannelTreeList()
        this.getChannelShopTreeList()
        this.search()
      }
    }
  },
  created() {
    // this.searchList[3].channelId = this.channelId
    this.getChannelTreeList()
    this.getChannelShopTreeList()
  },
  mounted() {
    this.setOption()
    this.searchData = {
      channelId: this.channelId,
      channelBrandId: '',
      pageNum: 0,
      pageSize: 10
    }
    this.dataList = []

    this.search()
  },
  methods: {
    selectable({ goodsType }) {
      return Boolean(this.filterHandle(goodsType))
    },
    filterHandle(goodsType, data) {
      let is = true
      if (data) {
        if (Number(data.lastPushResult) === 0) is = false
      }
      return ((window.appConfig.hiddenNewProducts && goodsType === 'DROPSHIPPING') || !window.appConfig.hiddenNewProducts) && is
    },
    setOption() {
      this.options.goodsType = []
      if (this.isAdministration) this.options.goodsType = goodsTypeList
      else {
        if (this.hasAuthority) this.options.goodsType.push(...goodsType_NO_CBEC)
        if (this.isECOperate) this.options.goodsType.push(...goodsType_CBEC)
      }
    },
    handleChange(value) {
      if (value && value.length) {
        const nodes = this.$refs.cascader.getCheckedNodes()
        const list = []
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i]
          if (!node.hasChildren) {
            list.push({
              shopCategoryId: node.value,
              shopCategoryName: node.label
            })
          }
        }
        this.skuCategories = list
      }
    },
    renderSkuCategory(data) {
      return data
        ?.map((_) => _.categoryName)
        .filter((_) => _)
        .join('、')
    },
    renderSkuCategoryTo(data) {
      // console.log('***********', data)
      return data
        ?.map((_) => _.shopCategoryName)
        .filter((_) => _)
        .join('、')
    },
    async getChannelTreeList() {
      const { result, code } = await queryChannelTreeList({ channelId: this.channelId })
      if (Array.isArray(result)) this.options.categoryId = result
      return code
    },
    async getChannelShopTreeList() {
      const { result } = await queryTreeList({ channelId: this.channelId })
      if (!Array.isArray(result)) return
      this.options.shopCategoryId = result
    },
    async refreshGetChannelTreeList(){
      const code = await this.getChannelTreeList()
      if (code === '0') this.$message.success('重新刷新店内类目成功！')
    },
    handleSearch() {
      this.searchData.pageNum = 0
      this.search()
    },
    async search() {
      this.$refs.table.clearSelection()
      try {
        this.loading = true
        const searchData = JSON.parse(JSON.stringify(this.searchData))
        if (searchData.categoryId) searchData.categoryId = searchData.categoryId[searchData.categoryId.length - 1]
        if (searchData.shopCategoryId) searchData.shopCategoryId = searchData.shopCategoryId[searchData.shopCategoryId.length - 1]
        searchData.skuList = stringToArray(searchData.skuList, /[\n\r]/) // upc(不含检验码)
        if (searchData.skuList.length === 0) delete searchData.skuList
        if (searchData.channelBrandId === '') delete searchData.channelBrandId
        if (!window.hidden_CBEC_iteration && !this.isAdministration) {
          searchData.notInGoodsType = []
          if (!this.isECOperate) searchData.notInGoodsType.push(...goodsType_CBEC.map((_) => _.value))
          if (!this.hasAuthority) searchData.notInGoodsType.push(...goodsType_NO_CBEC.map((_) => _.value))
        }
        if (searchData.skuList && searchData.skuList.length > 50) return this.$message.error('一次查询仅支持50条')
        const { result } = await findChgSkuChannelPage(searchData, this.menuName)
        if (!result) {
          this.dataList = []
          this.total = 0
          return
        }
        result.data.forEach((item) => {
          if (!item.hasOwnProperty(`lastPushResult`) || (item.hasOwnProperty(`lastPushResult`) && item.lastPushResult !== '0' && !item.lastPushResult)) {
            item.lastPushResult = '1'
          }
        })
        if (result) {
          this.total = result.total
          this.dataList = result.data
        } else {
          this.total = 0
          this.dataList = []
        }
      } finally {
        this.loading = false
      }
    },
    handlePageChange(param) {
      this.searchData.pageNum = param.pageNum - 1
      this.searchData.pageSize = param.pageSize
      this.search()
    },
    selectionChange(val) {
      this.multipleSelection = val
    },
    edit(scope) {
      eventBus.$emit('setTagName', scope.row.skuName)
      const url = `/commodityM/commodityEdit/${scope.row.upc}/edit/${this.$route.name}/${scope.row.channelId}`
      // if (this.menuName === 'JDWX') {
      //   url = `/commodityM/commodityEdit/${scope.row.upcNbr}/edit/${this.$route.name}/${scope.row.skuChannelInfo.channelId}`
      // }
      if (scope.row.goodsType === 'CBEC-DROP') {
        this.$router.push({
          path: `/CBEC/edit/${scope.row.upc}/edit/${this.$route.name}/${this.menuName}`,
          query: {
            channelId: scope.row.channelId,
            processId: scope.row.processId
          }
        })
        return
      }
      this.$router.push({
        path: url,
        query: { tab: this.menuName }
      })
    },
    batchEdit(type) {
      if (type === 'edit') {
        this.title = '批量修改店内类目'
      } else {
        this.title = '批量发布渠道'
      }
      this.form = {}
      this.btnloading = false
      this.dialogVisible = true
    },
    async onSubmit(formName) {
      let bol = false
      this.$refs[formName].validate((valid) => {
        if (valid) {
          bol = true
        } else {
          return false
        }
      })
      if (bol) {
        this.btnloading = true
        if (this.title === '批量修改店内类目') {
          await this.batchEditSubmitForm()
        } else {
          await this.batchUpdateChannel()
        }
        this.btnloading = false
        this.dialogVisible = false
      }
    },
    async batchEditSubmitForm() {
      const upcList = []
      this.multipleSelection.forEach((item) => {
        upcList.push(item.upc)
      })
      const param = {
        upcNbrList: upcList,
        channelId: this.channelId,
        shopCategories: this.skuCategories,
        batchOperationType: this.form.batchOperationType
      }
      const { result } = await batchUpdateSkuShopCatByChannel(param)
      if (result) {
        this.$message({
          type: 'success',
          message: '编辑成功！'
        })
      }
      this.handlePageChange({ pageNum: 1, pageSize: 10 })
    },
    async batchUpdateChannel() {
      const upcList = []
      this.multipleSelection.forEach((item) => {
        upcList.push(item.upc)
      })
      const param = {
        upcNbrList: upcList,
        channelId: this.channelId,
        operationRemark: this.form.operationRemark,
        updateBy: this.$store.getters.userId,
        updateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      }
      const { result } = await skuRepublishByChannel(param)
      if (result) {
        this.$message({
          type: 'success',
          message: '发布渠道成功!'
        })
        this.handlePageChange({ pageNum: 1, pageSize: 10 })
      }
    },
    // 重置检索条件
    reset() {
      const pageSize = this.searchData.pageSize
      this.searchData = {
        channelId: this.channelId,
        channelBrandId: '',
        pageSize,
        pageNum: 0
      }
      this.search()
    },
    // 导出
    async download() {
      // const date = moment(new Date()).format('YYYY-MM-DD')
      switch (this.menuName) {
        case 'WMDJ':
          break
        case 'JDDJ':
          break
        default:
          break
      }
    },
    // 操作日志
    async operationLog({ row }) {
      console.log('row', row)
      const obj = {
        channelId: row.channelId,
        upc: row.upc
      }
      // if (this.menuName === 'JDWX') {
      //   obj.channelId = row.skuChannelInfo.channelId
      //   obj.upc = row.upcWoCd
      // }
      const { result } = await operationLogByUpcNbr(obj)
      if (Array.isArray(result) && result.length) {
        this.$refs.operationLogRef.dialogVisible = true
        this.logData = result
      } else {
        this.$message({
          type: 'warning',
          message: '未查询到该渠道商品的操作日志'
        })
      }
    },
    viewDetail(row) {
      eventBus.$emit('setTagName', row.skuName)
      if (row.goodsType === 'CBEC-DROP') {
        this.$router.push({
          path: `/CBEC/edit/${row.upc}/detail/${this.$route.name}/${this.menuName}`,
          query: {
            channelId: row.channelId,
            processId: row.processId
          }
        })
        return
      }
      this.$router.push({
        path: `/commodityM/commodityEdit/${row.upc}/detail/${this.$route.name}/${row.channelId}`
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.mainImg {
  width: 50px;
  height: 50px;
}

.el-icon-refresh {
  font-size: 18px;
  cursor: pointer;
  margin-left: 10px;
}
</style>
